<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/4/24
 * Time: 16:46
 */

namespace app\admin\controller;

use app\admin\model\User as UserModel;

class User extends Base
{
    private $model;

    public function _initialize()
    {
        $this->model = new UserModel();
    }

    public function index()
    {
        if (request()->isAjax()) {
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            $where['status'] = 0;
            if (!empty($param['searchText'])) {
                $where['username'] = ['like', '%' . $param['searchText'] . '%'];
            }
            $selectResult = $this->model->getUserByWhere($where, $offset, $limit);
            //获取配置文件中状态
            $status = config('code.status_normal');
//            dump($selectResult);
            //拼接参数
            foreach ($selectResult as $k => $v) {
                //根据生日求年龄
                $selectResult[$k]['age'] = birthday($v['birthday']);
                //将用户表中的状态码 转为文字形式
                $selectResult[$k]['status'] = $status[$v['status']];
                $selectResult[$k]['headurl'] = '<img src="' . $v['headurl'] . '" width="40px" height="40px">';
                $selectResult[$k]['operate'] = showOperate($this->makeButton($v['id']));
            }
            $result['total'] = $this->model->getAllUser($where);//总数据
            $result['rows'] = $selectResult;
//            dump($result);die;
            return json($result);
        }
        return $this->fetch();
    }

    public function add()
    {
        if (request()->isPost()) {
            $param = input('post.');

            unset($param['file']);
            unset($param['files']);
            $number = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
            $param['usernumber'] = $number;
            $flag = $this->model->addUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $this->assign('status', config('sex.sex_status'));
        $this->assign('restatus', config('restatus.restatus'));
        $this->assign('is_show', config('is_show.is_show'));
        $this->assign('isfew', config('minority.few'));
        return $this->fetch();
    }

    public function edit()
    {

        if (request()->isPost()) {
            $param = input('post.');

            unset($param['file']);
            unset($param['files']);
            $flag = $this->model->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
//        dump($this->model->getOneUser($id));exit;
        $this->assign([
            'data' => $this->model->getOneUser($id),
            'status' => config('code.status_normal'),
            'sex' =>config('sex.sex_status'),
            'viplevel' => config('viplevel.viplevel'),
        ]);
        return $this->fetch();
    }

    public function uploadImg()
    {
        if (request()->isAjax()) {
            $file = request()->file('file');
            $data = input('post.');
            $path = 'head';

            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload/'.$path);
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($info) {
                $src = '/upload/'. $path . '/' . date('Ymd') . '/' . $info->getFilename();
                return json(msg(0, ['src' => $src], ''));
            } else {
                // 上传失败获取错误信息
                return json(msg(-1, '', $file->getError()));
            }
        }
    }

    public function video()
    {
        if (request()->isAjax()) {

            $file = $_FILES['files'];
            // 移动到框架应用根目录/public/uploads/ 目录下
            $param1 = input('post.param1');
            $param2 = input('post.param2');
            $data = array('sta'=>TRUE,'msg'=>'上传成功！');
            $ext = $this->getExt($file['name']);
            $arrExt = array('3gp','rmvb','flv','wmv','avi','mkv','mp4','mp3','wav');
            if(!in_array($ext,$arrExt)) {
                $data['sta'] = FALSE;
                $data['msg'] = '不支持此类型文件的上传！';
            }
            //设置预览目录
            $previewPath = 'upload/video/';
            $this->creatDir($previewPath);
//dump($file);die;
            if($file['error'] == 0) {
                if(isset($param1) && isset($param2)) {
                    //需要用到$param1和$param2的一些其他操作...

                    //文件上传到预览目录
                    $previewName = 'pre_'.md5(mt_rand(1000,9999)).time().'.'.$ext;
                    $previewSrc = $previewPath.$previewName;
//                    dump($previewSrc);die;
                    if(!move_uploaded_file($file['tmp_name'],$previewSrc)) {
                        $data['sta'] = FALSE;
                        $data['msg'] = '上传失败！';
                    } else {
                        $data['previewSrc'] = '/upload/video/'.$previewName;
                    }
                }
            }
//            dump($data);die;
            echo json_encode($data);
        }
    }

    //获取文件扩展名
    function getExt($filename) {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        return $ext;
    }

    //创建目录并赋权限
    function creatDir($path) {
        $arr = explode('/',$path);
        $dirAll = '';
        $result = FALSE;
        if(count($arr) > 0) {
            foreach($arr as $key=>$value) {
                $tmp = trim($value);
                if($tmp != '') {
                    $dirAll .= $tmp.'/';
                    if(!file_exists($dirAll)) {
                        mkdir($dirAll,0777,true);
                    }
                }
            }
        }
    }

    public function del()
    {
        if ($this->request->isGet()) {
            $id = input('param.id');
            $flag = $this->model->saveStatus($id);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'User/edit',
                'href' => url('User/edit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'User/del',
                'href' => "javascript:adminDel(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }
}